import http2 from 'node:http2'
import fs from 'node:fs'
import express from 'express'

// 在 02目录下运行 node app.js  否则上下文不对，读取下面的文件目录不对
const options = {
  key: fs.readFileSync('./server.key'),
  cert: fs.readFileSync('./server.crt')
}
const app = express()

app.use(express.static('./public'))


// 创建 HTTPS 服务器并启用 HTTP/2
const server = http2.createSecureServer(options)

server.on('stream', (stream, headers, flags) => {
  console.log(flags);
  app(stream, headers, (err) => {
    if (err) {
      stream.respond({ ':status': 500, 'content-type': 'text/plain' }, err.message);
      return;
    }

    // 响应头部和结束流
    stream.respond(headers);
    stream.end('Hello World\n');
  })
})


server.listen(5000, () => {
  console.log('Server running on https://localhost:5000');
})

/**
 node: 20.10.0 在这个express版本会报错

 应该是 express的问题， 大概率是  app.use(express.static('./public'))

 没有返回符合 http2的合适的响应头

 目前从 issue看： https://github.com/expressjs/express/issues/5462  express 4.x版本是不能和 http2结合

 node:internal/http2/util:461
    throw new ERR_HTTP2_INVALID_PSEUDOHEADER(key);
    ^

TypeError [ERR_HTTP2_INVALID_PSEUDOHEADER]: ":method" is an invalid pseudoheader or is used incorrectly
 */